package com.example.routeplansystem.service.impl;

import com.example.routeplansystem.constant.PageRes;
import com.example.routeplansystem.dao.ProgramDao;
import com.example.routeplansystem.entity.dto.AFile;
import com.example.routeplansystem.entity.po.Program;
import com.example.routeplansystem.entity.vo.ProgramRes;
import com.example.routeplansystem.service.ProgramService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author lucong
 * @Date 2022/10/31
 * @Description
 */
@Service
@Slf4j
public class ProgramServiceImpl implements ProgramService {

    @Autowired
    private ProgramDao programDao;

    @Value("${algorithm.file.path}")
    private String path;

    @Override
    public ProgramRes getProgramById(Integer id) {
        Program program = programDao.getProgramById(id);
        ProgramRes programRes = new ProgramRes();
        BeanUtils.copyProperties(program, programRes);
        File parent = new File(path + File.separator + id);
        File[] files = parent.listFiles();
        if (files == null) files = new File[0];
        List<AFile> fileList = new ArrayList<>(files.length);
        for (File file : files) {
            AFile aFile = new AFile(file);
            fileList.add(aFile);
        }
        programRes.setFileList(fileList);
        return programRes;
    }

    @Override
    public PageRes<Program> pageProgramByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        Page<Program> page =
                PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> programDao.selectProgramByUserId(userId));
        return new PageRes<>(page);
    }
}
